package agan.rpc.protocol;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {
    public String send(String host, int port, Invocation invocation) {
        String result = null;
        try {
            URL url = new URL("http", host, port, "/");
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);

            OutputStream out = httpConnection.getOutputStream();
            ObjectOutputStream outStream = new ObjectOutputStream(out);
            outStream.writeObject(invocation);
            outStream.flush();
            outStream.close();

            InputStream inputStream = httpConnection.getInputStream();
            result =  IOUtils.toString(inputStream);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
